package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.AlertDataPageDTO;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;

/**
 * 报警数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-28
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService
{
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     * 
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     * 
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Autowired
    private ISysUserService userService;
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData)
    {
        List<AlertData> alertDataList = alertDataMapper.selectAlertDataList(alertData);
        for (AlertData data : alertDataList) {
            SysUser sysUser = userService.selectUserById(data.getUserId());
            data.setPreProcessorName(sysUser.getUserName());
        }
        return alertDataList;
    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
//    @Override
//    public int updateAlertData(AlertData alertData)
//    {
//        return updateById(alertData) ? 1 : 0;
//    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 分页查询报警数据列表
     *
     * @param dto 查询参数
     * @return
     */
    @Override
    public List<AlertData> pageList(AlertDataPageDTO dto) {
        List<AlertData> list = this.lambdaQuery()
                .eq(dto.getStatus()!=null,AlertData::getStatus, dto.getStatus())
                .eq(dto.getUserId() != 1,AlertData::getUserId, dto.getUserId())
                .eq(dto.getDeviceName()!=null,AlertData::getDeviceName,dto.getDeviceName())
                .between(dto.getStartTime()!=null && dto.getEndTime()!=null,AlertData::getCreateTime,dto.getStartTime(),dto.getEndTime())
                .list();
        for (AlertData data : list) {
            SysUser sysUser = userService.selectUserById(data.getUserId());
            data.setPreProcessorName(sysUser.getNickName());
        }
        return list;
    }

    @Transactional
    @Override
    public void handleAlertData(AlertDataDto alertData) {
        AlertData one = this.lambdaQuery().eq(AlertData::getId, alertData.getId()).one();
        if (one == null){
            throw new BaseException("这个警报已被处理");
        }
        LocalDateTime localDateTime = LocalDateTime.ofInstant(
                Instant.parse(alertData.getProcessingTime()),
                ZoneId.of("Asia/Shanghai")
        );
        AlertData updateObj = new AlertData();
        updateObj.setProcessorId(SecurityUtils.getUserId());
        updateObj.setProcessorName(SecurityUtils.getUsername());
        updateObj.setProcessingResult(alertData.getProcessingResult());
        updateObj.setProcessingTime(localDateTime);
        updateObj.setStatus(1);


        boolean updated = this.update(updateObj,
                Wrappers.<AlertData>lambdaUpdate()
                        .eq(AlertData::getIotId, one.getIotId())
                        .eq(AlertData::getProductKey, one.getProductKey())
                        .eq(AlertData::getFunctionId, one.getFunctionId())
                        .eq(AlertData::getStatus, 0) //业务层乐观锁
        );
        //  检查是否真的有数据被更新
        if (!updated) {
            // 理论上不会走到这里（因为前面判断存在），但并发极端情况下可能
            throw new BaseException("处理失败：报警已被他人处理");
        }
    }
}
